<template>
  <div class="student-container">
    <el-card shadow="never">
      <!-- 搜索栏 -->
      <div class="filter-header">
        <el-input 
          v-model="filter.studentId" 
          placeholder="学生学号"
          style="width: 160px"
          class="filter-item"
        />
        <el-input 
          v-model="filter.studentName" 
          placeholder="学生姓名"
          style="width: 160px; margin-left: 10px"
          class="filter-item"
        />
        <el-button 
          type="primary" 
          style="margin-left: 15px"
          @click="handleSearch">
          搜索 
        </el-button>
        <el-button 
          style="margin-left: 10px"
          @click="resetFilter">
          重置 
        </el-button>
      </div>
  
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button 
          type="primary" 
          :icon="CirclePlus"
          @click="showDialog('add')">
          新增 
        </el-button>
      </div>
  
      <!-- 数据表格 -->
      <el-table 
        :data="tableData"
        style="width: 100%"
        header-row-class-name="table-header"
      >
        <!-- 表格列 -->
        <el-table-column prop="id" label="学生学号 ▲" width="120" sortable>
          <template #default="scope">
            <span>{{ scope.row.id  }}</span>
            <el-icon color="#409EFF" style="margin-left: 3px"><CaretTop /></el-icon>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="学生姓名" width="120"/>
        <el-table-column prop="gender" label="学生性别" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getGenderColor(scope.row.gender)"  size="small">
              {{ scope.row.gender  }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="birthdate" label="出生日期" width="120"/>
        <el-table-column prop="score" label="入学成绩" width="120" align="center"/>
        <el-table-column prop="department" label="所在系" width="180"/>
        <el-table-column label="操作" width="150" align="center">
          <template #default="scope">
            <el-button 
              type="text" 
              :icon="Edit" 
              style="color: #67C23A"
              @click="showDialog('edit', scope.row)"> 
              编辑 
            </el-button>
            <el-button 
              type="text" 
              :icon="Delete" 
              style="color: #F56C6C"
              @click="handleDelete(scope.row.id)"> 
              删除 
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 分页信息 -->
      <div class="pagination-info">
        第 1 到 {{ tableData.length  }} 条，共 {{ tableData.length  }} 条记录。
      </div>
  
      <!-- 学生信息对话框 -->
      <el-dialog 
        :title="dialogType === 'add' ? '新增学生' : '编辑学生'"
        v-model="dialogVisible"
        width="600px"
        @closed="resetForm">
        <el-form 
          :model="formData" 
          :rules="formRules" 
          ref="studentForm"
          label-width="100px">
          <el-form-item label="学生学号" prop="id">
            <el-input v-model="formData.id"  :disabled="dialogType === 'edit'"/>
          </el-form-item>
          <el-form-item label="学生姓名" prop="name">
            <el-input v-model="formData.name"/> 
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-select v-model="formData.gender"  placeholder="请选择">
              <el-option label="男" value="男"/>
              <el-option label="女" value="女"/>
              <el-option label="未知" value="未知"/>
            </el-select>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthdate">
            <el-date-picker 
              v-model="formData.birthdate" 
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"/>
          </el-form-item>
          <el-form-item label="入学成绩" prop="score">
            <el-input-number 
              v-model="formData.score"  
              :min="0" 
              :max="750"
              controls-position="right"/>
          </el-form-item>
          <el-form-item label="所在系" prop="department">
            <el-input v-model="formData.department"/> 
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>
 
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { CirclePlus, Edit, Delete, CaretTop } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
 
// 状态管理 
const filter = reactive({
  studentId: '',
  studentName: ''
})
 
const tableData = ref([
  { id: 1, name: '沿停', gender: '女', birthdate: '2020-01-17', score: 666, department: '计算机科学与技术' },
  { id: 48, name: '王旭', gender: '男', birthdate: '2020-01-03', score: 666, department: '计算机科学与技术' },
  { id: 49, name: '高钰清', gender: '女', birthdate: '2020-01-07', score: 666, department: '网络工程' },
  { id: 50, name: '黄灿', gender: '男', birthdate: '2019-12-29', score: 666, department: '物联网工程' },
  { id: 51, name: '张庆阳', gender: '未知', birthdate: '2020-01-11', score: 666, department: '软件工程' },
  { id: 52, name: '张凤辰', gender: '女', birthdate: '2020-01-06', score: 666, department: '网络工程' }
])
 
const originalData = ref([])
const dialogVisible = ref(false)
const dialogType = ref('add')
const studentForm = ref(null)
 
const formData = reactive({
  id: '',
  name: '',
  gender: '',
  birthdate: '',
  score: 666,
  department: ''
})
 
const formRules = reactive({
  id: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  department: [{ required: true, message: '请输入所在系', trigger: 'blur' }]
})
 
// 方法 
const getGenderColor = (gender) => {
  return gender === '女' ? 'danger' : gender === '男' ? 'primary' : 'info'
}
 
const handleSearch = () => {
  tableData.value  = originalData.value.filter(item  => {
    const idMatch = item.id.toString().includes(filter.studentId) 
    const nameMatch = item.name.includes(filter.studentName) 
    return idMatch && nameMatch 
  })
}
 
const resetFilter = () => {
  filter.studentId  = ''
  filter.studentName  = ''
  tableData.value  = [...originalData.value] 
}
 
const showDialog = (type, row) => {
  dialogType.value  = type 
  if (type === 'edit') {
    Object.assign(formData,  row)
  }
  dialogVisible.value  = true 
}
 
const submitForm = async () => {
  try {
    await studentForm.value.validate() 
    
    if (dialogType.value  === 'add') {
      tableData.value.push({  ...formData })
    } else {
      const index = tableData.value.findIndex(item  => item.id  === formData.id) 
      tableData.value[index]  = { ...formData }
    }
    
    dialogVisible.value  = false 
    ElMessage.success(' 操作成功')
  } catch (error) {
    console.error(' 表单验证失败:', error)
  }
}
 
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm(' 确认删除该学生信息？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    tableData.value  = tableData.value.filter(item  => item.id  !== id)
    ElMessage.success(' 删除成功') 
  } catch {
    // 用户取消删除 
  }
}
 
const resetForm = () => {
  if (studentForm.value)  {
    studentForm.value.resetFields() 
  }
  formData.id  = ''
  formData.name  = ''
  formData.gender  = ''
  formData.birthdate  = ''
  formData.score  = 666 
  formData.department  = ''
}
 
// 初始化 
onMounted(() => {
  originalData.value  = JSON.parse(JSON.stringify(tableData.value)) 
})
</script>
 
<style scoped>
.student-container {
  padding: 20px;
}
 
.filter-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
 
.filter-item {
  margin-left: 10px;
}
 
.action-buttons {
  margin: 15px 0;
}
 
.table-header th {
  background-color: #f5f7fa !important;
  font-weight: 600;
}
 
.pagination-info {
  margin-top: 15px;
  color: #909399;
  font-size: 13px;
  text-align: center;
}
 
.el-tag {
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
}
 
.el-button--text {
  padding: 0 5px;
}
 
.el-icon-caret-top {
  vertical-align: middle;
}
</style>